let chats = [];
let activeChat = null;

// 创建聊天容器的HTML模板
function createChatContainerHTML(chatId) {
  return `
    <div class="chat-container" id="chat-${chatId}">
      <div class="message-container" id="messages-${chatId}"></div>
      <div class="input-group">
             <select
            class="form-select me-3"
            id="knowledgeSelect"
            style="width: 200px"
          >
            <option value="">请选择知识库</option>
          </select>
        <input type="text" id="userInput-${chatId}" placeholder="输入您的问题..." />
        <button onclick="sendMessage(${chatId})">发送</button>
      </div>
    </div>
  `;
}

// 创建新的聊天会话
function createNewChat() {
  const chatId = Date.now(); // 使用时间戳作为会话ID
  const chat = {
    id: chatId,
    messages: []
  };

  chats.push(chat);

  // 创建新的标签页
  const tabsContainer = document.getElementById('chatTabs');
  const tab = document.createElement('div');
  tab.className = 'tab';
  tab.setAttribute('data-chat-id', chatId);
  tab.innerHTML = `
    会话 ${chats.length}
    <span class="tab-close" onclick="closeChat(event, ${chatId})">×</span>
  `;
  tab.onclick = (e) => {
    if (!e.target.classList.contains('tab-close')) {
      switchChat(chatId);
    }
  };
  tabsContainer.insertBefore(tab, document.querySelector('.new-chat-btn'));

  // 创建新的聊天容器
  const chatContainers = document.getElementById('chatContainers');
  chatContainers.insertAdjacentHTML(
    'beforeend',
    createChatContainerHTML(chatId)
  );

  // 切换到新创建的会话
  switchChat(chatId);
}

// 切换聊天会话
function switchChat(chatId) {
  // 更新标签页状态
  document.querySelectorAll('.tab').forEach((tab) => {
    tab.classList.remove('active');
    if (tab.getAttribute('data-chat-id') == chatId) {
      tab.classList.add('active');
    }
  });

  // 更新聊天容器显示状态
  document.querySelectorAll('.chat-container').forEach((container) => {
    container.classList.remove('active');
  });
  document.getElementById(`chat-${chatId}`).classList.add('active');

  activeChat = chatId;

  // 聚焦输入框
  document.getElementById(`userInput-${chatId}`).focus();
}

// 关闭聊天会话
function closeChat(event, chatId) {
  event.stopPropagation();

  // 移除标签页
  const tab = document.querySelector(`.tab[data-chat-id="${chatId}"]`);
  tab.remove();

  // 移除聊天容器
  const container = document.getElementById(`chat-${chatId}`);
  container.remove();

  // 从数组中移除会话
  chats = chats.filter((chat) => chat.id !== chatId);

  // 如果关闭的是当前活动的会话，切换到最后一个会话
  if (activeChat === chatId && chats.length > 0) {
    switchChat(chats[chats.length - 1].id);
  }
}

// 添加消息到聊天窗口
function addMessage(content, type, chatId) {
  const messageDiv = document.createElement('div');
  messageDiv.className = `message ${type}`;
  messageDiv.innerHTML = content;
  document.getElementById(`messages-${chatId}`).appendChild(messageDiv);
  messageDiv.scrollIntoView({ behavior: 'smooth' });
  return messageDiv;
}

// 发送消息
async function sendMessage(chatId) {
  const input = document.getElementById(`userInput-${chatId}`);
  const message = input.value.trim();
  // const responseType = document.getElementById(`responseType-${chatId}`).value;

  if (message) {
    addMessage(`你: ${message}`, 'user', chatId);
    input.value = '';

    const data = {
      message: message,
      conversationId: chatId
    };

    // 如果选择了知识库，则添加知识库ID
    const knowledgeId = $('#knowledgeSelect').val();
    if (knowledgeId) {
      data.knowledgeId = knowledgeId;
    }
    let responseType = '/chat/stream'
    const response = await fetch(responseType, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    });

    let assistantMessageDiv = addMessage('', 'assistant', chatId);

    if (responseType === '/chat') {
      const result = await response.text();
      assistantMessageDiv.innerHTML = result;
    } else {
      const reader = response.body.getReader();
      const decoder = new TextDecoder('utf-8');
      let result = '';

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        const chunk = decoder.decode(value, { stream: true });

        result += chunk;
        const processedChunk = result
          .replace(/<think>/g, '<div class="think">')
          .replace(/<\/think>/g, '</div>');
        assistantMessageDiv.innerHTML = processedChunk;
      }
    }
  }
}

// 加载知识库列表
function loadKnowledgeList() {
  $.ajax({
    url: '/knowledge/list',
    method: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({
      pageNo: 1,
      pageSize: 1000
    }),
    success: function (response) {
      if (response.code === 200) {
        let html = '<option value="">请选择知识库</option>';
        response.data.forEach(function (item) {
          html += `<option value="${item.id}">${item.name}</option>`;
        });
        $('#knowledgeSelect').html(html);
      }
    }
  });
}

// 知识库选择变化时的处理
$('#knowledgeSelect').on('change', function () {
  const knowledgeId = $(this).val();
  localStorage.setItem('currentKnowledgeId', knowledgeId);
});

// 为每个聊天窗口添加回车发送功能
document.addEventListener('keypress', (event) => {
  if (event.key === 'Enter' && activeChat) {
    const activeInput = document.getElementById(`userInput-${activeChat}`);
    if (document.activeElement === activeInput) {
      sendMessage(activeChat);
    }
  }
});

// 页面加载完成后初始化
$(document).ready(function () {
  loadKnowledgeList();
  createNewChat();
});
